package com.kaiwukj.android.ufamily.utils;

import android.media.MediaPlayer;

import java.io.File;
import java.io.IOException;

/**
 * @author Charles
 * @date 2019/8/16.
 * description：Kaiwu
 */
public class AudioUtils {
    public static int getAmrDuration(File file) throws IOException {

        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(file.toString());
        mediaPlayer.prepare();
        int nDuration0 = mediaPlayer.getDuration();// 单位毫秒

        return nDuration0 / 1000;

//        long duration = -1;
//        int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
//                0, 0 };
//        RandomAccessFile randomAccessFile = null;
//        try {
//            randomAccessFile = new RandomAccessFile(file, "rw");
//            // 文件的长度
//            long length = file.length();
//            // 设置初始位置
//            int pos = 6;
//            // 初始帧数
//            int frameCount = 0;
//            int packedPos = -1;
//            // 初始数据值
//            byte[] datas = new byte[1];
//            while (pos <= length) {
//                randomAccessFile.seek(pos);
//                if (randomAccessFile.read(datas, 0, 1) != 1) {
//                    duration = length > 0 ? ((length - 6) / 650) : 0;
//                    break;
//                }
//                packedPos = (datas[0] >> 3) & 0x0F;
//                pos += packedSize[packedPos] + 1;
//                frameCount++;
//            }
//            // 帧数*20
//            duration += frameCount * 20;
//        } finally {
//            if (randomAccessFile != null) {
//                randomAccessFile.close();
//            }
//        }
//        return (int)((duration/1000));
    }

    public static int getNetAudioTime(String url) throws IOException {
        MediaPlayer mediaPlayer = new MediaPlayer();
        int s = 0;
        mediaPlayer.setDataSource(url);

        mediaPlayer.prepare();
        int duration = mediaPlayer.getDuration();
        if (0 != duration) {

            s = duration / 1000;
            //记得释放资源
            mediaPlayer.release();
        }
        return s;
    }
}
